package com.saltedfish.tool.ui.flag

import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import android.widget.Toast
import cn.droidlover.xdroidmvp.base.SimpleListener
import cn.droidlover.xdroidmvp.event.BusProvider
import cn.droidlover.xdroidmvp.log.XLog
import cn.droidlover.xdroidmvp.popwindow.AlertButtonDialog
import cn.droidlover.xdroidmvp.util.ActivityManager
import cn.droidlover.xdroidmvp.util.AppUtil
import cn.droidlover.xdroidmvp.util.ToastUtils
import com.blankj.rxbus.RxBus
import com.saltedfish.tool.R
import com.saltedfish.tool.dao.*
import com.saltedfish.tool.dialog.UICreateSonFlagDialog
import com.saltedfish.tool.dialog.UIFlagDoneDialog
import com.saltedfish.tool.model.ModelInfo
import com.saltedfish.tool.model.SmallTable
import com.saltedfish.tool.present.SonFlagDetailAP
import com.saltedfish.tool.ui.XActivity
import com.saltedfish.tool.util.DateUtils
import com.saltedfish.tool.util.ViewClickUtils
import kotlinx.android.synthetic.main.activity_son_flag_detail.*
import java.text.SimpleDateFormat
import java.util.*

class SonFlagDetailActivity : XActivity<SonFlagDetailAP>(), View.OnClickListener {


    override fun getLayoutId(): Int {
        setStatusColor(true, 1)
        setStatusBlack()
        return R.layout.activity_son_flag_detail
    }

    private var subId: String? = null
    private var flagId: String? = null
    private var status: String? = null

    private var database: AppDatabase? = null
    private  var subFlagDao : SubFlagModelDao? =null
    var flagModelDao: FlagInfoDao? = null
    private  var dayDBDao : DayDBDao? =null

    private var subFlagModel: SmallTable? = null
    var cal: Calendar? = null

    private  var day : Long? =0
    private var flagDone : Boolean = false

    override fun initData(savedInstanceState: Bundle?) {
        subId = intent.getStringExtra("subId")
        status = intent.getStringExtra("status")

        database = AppDataUtils.initRoom(context)
        ViewClickUtils.setViewClick(this, tvBack)
        ViewClickUtils.setViewClick(this, tvDeltele)
        ViewClickUtils.setViewClick(this, btn_edit_flag)
        tvRepeatDate.text = "重复&时间"
        cal = Calendar.getInstance()
        cal!!.time =  Date()

        initDataShow(subId!!)

        BusProvider.getBus().subscribe(context,
                RxBus.Callback<ModelInfo> { modelInfo ->
                    if (modelInfo != null && modelInfo.updateFlag) {
                        subId = modelInfo.subId
                        flagDone = true
                        initDataShow(modelInfo.subId)
                    }
                })

    }


    private fun  initDataShow(subIds: String){
        if(database !=null){
            flagModelDao = database!!.flagInfoDao()
            subFlagDao = database!!.subFlagDao()
            dayDBDao = database!!.dayDBDao()
//            XLog.e("--subIds---$subIds")
//           var list =  dayDBDao!!.all
//            XLog.e("--all---$list")

            subFlagModel = subFlagDao!!.getBySubId(subIds)
       //    XLog.e(subIds+"--subFlagModel---"+subFlagModel.toString())
            flagId = subFlagModel!!.fId
            tvFlagTitile.text = subFlagModel!!.title

            val startTime = DateUtils.strToDateStr(subFlagModel!!.startTime)
            tvFlagStartDate.text = DateUtils.getStringByDate(startTime)

            if(TextUtils.isEmpty(subFlagModel!!.endTime)){
                releateFlagEndDate.visibility = View.GONE
            }else{
                releateFlagEndDate.visibility = View.VISIBLE
                val endTime = DateUtils.strToDateStr(subFlagModel!!.endTime)
                tvFlagEndDate.text = DateUtils.getStringByDate(endTime)
            }

            if(TextUtils.isEmpty(subFlagModel!!.repeatDay)){
                tvWeek.text = "不重复"
                tvWeek.setTextColor(context.resources.getColor(R.color.color_3097FF))
            }else{
                tvWeek.setTextColor(context.resources.getColor(R.color.color_333333))
                val weeks = subFlagModel!!.repeatDay.split(" ").toTypedArray()
                if (weeks.size != 7) {
                    tvWeek.text = subFlagModel!!.repeatDay
                } else {
                    tvWeek.text = "每天"
                }
            }

            tvWeekDate.text = subFlagModel!!.repeatTime
            if(subFlagModel!!.isRemind){
                tvRemindCall.text = "提醒"
                tvRemindCall.setTextColor(context.resources.getColor(R.color.color_333333))
            }else{
                tvRemindCall.text = "不提醒"
                tvRemindCall.setTextColor(context.resources.getColor(R.color.color_3097FF))
            }

            //进行的状态
            var startT =  DateUtils.compareEqualsDate(subFlagModel!!.startTime, DateUtils.getStringDateShort())
            subFlagModel!!.progress = subFlagModel!!.tickNum.toFloat()/subFlagModel!!.tick.toFloat()

            if(startT != 0){
                day =  DateUtils.getDays(subFlagModel!!.endTime, DateUtils.getStringDateShort()) + 1

                    if(subFlagModel!!.progress >= 1.0f){
                        btn_edit_flag.visibility = View.GONE
                        tvStatus.text = "完成"
                        tvStatus.setTextColor(context.resources.getColor(R.color.color_333333))
                    }else{
                        var days = DateUtils.compareEqualsDate(subFlagModel!!.endTime, DateUtils.getStringDateShort())
                        if(days != 1){
                            if (subFlagModel!!.status == "暂停") {
                                tvStatus.text = "暂停"
                                tvStatus.setTextColor(context.resources.getColor(R.color.color_3097FF))

                            } else if (subFlagModel!!.status == "提前完成") {
                                tvStatus.text = "提前完成"
                                if(!flagDone){
                                    btn_edit_flag.visibility = View.GONE
                                }
                                tvStatus.setTextColor(context.resources.getColor(R.color.color_333333))
                            }else{
                                tvStatus.text = "进行中"
                                tvStatus.setTextColor(context.resources.getColor(R.color.color_333333))
                            }
                        }else{
                            tvStatus.text = "已延期"
                            tvStatus.setTextColor(context.resources.getColor(R.color.color_ED5656))
                        }
                     }
            }else{
                day =  DateUtils.getDays(subFlagModel!!.endTime, subFlagModel!!.startTime) + 1
                tvStatus.text =  "暂未开始"
                tvStatus.setTextColor(context.resources.getColor(R.color.color_3097FF))
            }

            if(day!! > 0){
                tvSurplusDay.text = day.toString() + "天"
            }else{
                tvSurplusDay.text = "0天"
            }
            XLog.e("-subFlagModel---${subFlagModel}-->>")
            if (subFlagModel!!.status == "提前完成") {
                tvStatus.text = "提前完成"

                if(status.equals("1")|| status.equals("2")){
                    if(!flagDone){
                        btn_edit_flag.visibility = View.GONE
                    }
                }else{
                    btn_edit_flag.visibility = View.VISIBLE
                }
                tvStatus.setTextColor(context.resources.getColor(R.color.color_333333))
                tvSpeedProgress.text = subFlagModel!!.completeDay + "完成"
            }else{
                if(subFlagModel!!.progress == null || subFlagModel!!.progress == 0f){
                    //完成进度
                    tvSpeedProgress.text = "0%"
                }else if(subFlagModel!!.progress == 1.0f){
                    btn_edit_flag.visibility = View.GONE
                    tvStatus.text = "完成"
                    tvStatus.setTextColor(context.resources.getColor(R.color.color_333333))
                    tvSpeedProgress.text = subFlagModel!!.completeDay + "完成"
//                    tvSpeedProgress.text = DateUtils.strToDateStr(subFlagModel!!.completeDay)+ "完成"
                }else{
                    tvSpeedProgress.text = String.format("%.1f", (subFlagModel!!.progress * 100)) + "%"
                }
            }

        }
    }


    override fun newP(): SonFlagDetailAP? {
        return SonFlagDetailAP()
    }


    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tvBack -> {
                if(updateStates){
                     showFlagDialog(subFlagModels)
                }
                finish()
            }
            R.id.tvDeltele -> {
                deleteFlagDialog()
            }

            R.id.btn_edit_flag -> {
                initCreateSonFalgView(flagId!!)
            }

        }
    }

    private var  createSonFlagDialog : UICreateSonFlagDialog? =null

    private val mHandler = Handler()

    private var  updateStates : Boolean = false
    private var  subFlagModels : SmallTable = SmallTable()

    /**
     * 创建子目标
     */
    private fun initCreateSonFalgView(flagId: String) {

     //   if (createSonFlagDialog == null) {
            createSonFlagDialog = UICreateSonFlagDialog(context, flagId, database)
            createSonFlagDialog!!.setSimpleListener(object : SimpleListener<SmallTable>() {
                override fun onClick(subFlagModel: SmallTable) {
                    subFlagModels = subFlagModel
                    updateStates = false
//                    XLog.e("--subFlagModel--设置完成状态------$subFlagModel")
                    if (subFlagModel.status == "提前完成") {
                        updateStates = true
                        createSonFlagDialog!!.dismiss()
                    }
                }
            })
   //     }
          createSonFlagDialog!!.setOnKeyBackListener(false)
        createSonFlagDialog!!.updateFlag(subFlagModel!!.subId, flagId)
        createSonFlagDialog!!.show()

        mHandler.postDelayed(Runnable {
            AppUtil.showSoftInput(context)
        }, 500)

    }

    override fun onBackPressed() {
//        XLog.e("----333333--设置完成状态------"+updateStates)
        if(updateStates){
            showFlagDialog(subFlagModels)
        }
        finish()
    }


    private fun showFlagDialog(subFlagModel: SmallTable) {
        var flagLists =  subFlagDao!!.getAllByFlagId(subFlagModel.fId)

        var flagProgressList = subFlagDao!!.getAllByFlagIdAndProgress(subFlagModel.fId, 1.0f, "提前完成")
        var flagInfo =  flagModelDao!!.getById(subFlagModel.fId)
//        XLog.e("-------flagLists-------"+flagLists.size)
//        XLog.e("-------flagProgressList-------"+flagProgressList.size)

        if(flagLists.size == flagProgressList.size){
            flagInfo.isComplete =  true
            val sdf = SimpleDateFormat("yyyy/MM/dd")
            var  completeToday = sdf.format(cal!!.time)
            flagInfo.completeDay = completeToday
            flagModelDao!!.update(flagInfo)
            val modelInfo = ModelInfo()
            modelInfo.updateFlag = true
            modelInfo.flagDone = true
            modelInfo.type = 1
            modelInfo.title = flagInfo.title
            BusProvider.getBus().post(modelInfo)
        }else{
            flagInfo.isComplete =  false
            flagInfo.completeDay = ""
            flagModelDao!!.update(flagInfo)
            if(subFlagModel.progress == 1.0f || subFlagModel.status == "提前完成"){
               // initFlagDoneDialog(0, subFlagModel.title)
                val modelInfo = ModelInfo()
                modelInfo.updateFlag = true
                modelInfo.flagDone = true
                modelInfo.type = 0
                modelInfo.title = subFlagModel.title
                BusProvider.getBus().post(modelInfo)
            }
        }

    }




    /**
     * 删除弹窗
     */
    private fun deleteFlagDialog() {
        val dialog = AlertButtonDialog(context)
        dialog.builder()
        dialog.setTitle("删除子目标")
        dialog.setMsg("该子目标及其完成记录都将被删除,\n" +
                "确认要删除吗? ")
        dialog.setPositiveButton("确认"
        ) {  deleteFlag() }
        dialog.setNegativeButton("取消"
        ) { }
        dialog.show()
    }

    private fun deleteFlag() {
        if(subFlagDao !=null){
            subFlagDao!!.deleteSubFlagBySubId(subFlagModel!!.subId)
            dayDBDao!!.deleteAllBySubId(subId)
         //   CalendarReminderUtils.deleteCalendarEvent(context, subFlagModel!!.subId)
            var modelInfo = ModelInfo()
            modelInfo.updateFlag = true
            modelInfo.updateCalendar2 = true
            BusProvider.getBus().post(modelInfo)
            finish()
        }
    }


}
